package com.ridbor001.bank.controller;

import com.ridbor001.bank.bean.SafetyResult;
import com.ridbor001.bank.bean.SystemState;
import com.ridbor001.bank.service.AITeachingService;
import com.ridbor001.bank.service.BankersAlgorithmService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/bankers")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173")
public class AlgorithmController {

    private final BankersAlgorithmService bankersService;
    private final AITeachingService teachingService;

    @PostMapping("/check-safety")
    public ResponseEntity<SafetyResult> checkSafety(@RequestBody SystemState state) {
        SafetyResult result = bankersService.checkSafety(state);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/process-request")
    public ResponseEntity<SafetyResult> processRequest(
            @RequestBody SystemState state,
            @RequestParam int processId,
            @RequestBody List<Integer> request) {

        SafetyResult result = bankersService.processRequest(state, processId, request);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/explain-algorithm")
    public ResponseEntity<Map<String, String>> explainAlgorithm(@RequestBody SystemState state) {
        String explanation = teachingService.explainAlgorithmSteps(state);
        return ResponseEntity.ok(Map.of("explanation", explanation));
    }

    @PostMapping("/diagnose-deadlock")
    public ResponseEntity<Map<String, String>> diagnoseDeadlock(
            @RequestBody SystemState state,
            @RequestParam List<Integer> deadlockProcesses) {

        // 验证进程ID是否有效
        for (int pid : deadlockProcesses) {
            if (pid < 0 || pid >= state.getProcessCount()) {
                return ResponseEntity.badRequest().body(Map.of(
                        "error", "无效的进程ID: " + pid
                ));
            }
        }

        SafetyResult result = new SafetyResult(false, null, deadlockProcesses);
        String diagnosis = teachingService.diagnoseDeadlock(state, result);
        return ResponseEntity.ok(Map.of("diagnosis", diagnosis));
    }
}